var currentStatus:String;
var previewFillingMaskBar;
var cacheFillingMaskBar;
var progressFillingMaskBar;
var previewDuration:Number;
var currentFilteredAudioObj;
var timeDisplay:TextField;
var progressDisplay:TextField;

var playerEngineRunning:Boolean;
var convertorRunning:Boolean;

var onceFlag:Boolean;

function init(param, data, slot)
{
	var cont:String=Packages.system.MLF.scanDictionary(Packages.components.ReadingRecorder.recorderMain, "processResult09");
	Packages.components.ReadingRecorder.refreshResultContent(cont, false);
	var hlp:String=Packages.system.MLF.scanDictionary(Packages.components.ReadingRecorder.recorderMain, "recordHelpContent05");
	Packages.components.ReadingRecorder.refreshHelpContent(hlp);

	// init the timedisplay of preview audio
	previewDuration=Packages.task.Composition.processData.duration;
	timeDisplay=mlf.gatekeeper.native.Caller.scanElement(slot, "timedisplay");
	displayTimePeriod(timeDisplay, 0, previewDuration);
	progressDisplay=mlf.gatekeeper.native.Caller.scanElement(slot, "ptimedisplay");
	displayTimePeriod(progressDisplay, 0, previewDuration);
	
	var previewFillingBar=mlf.gatekeeper.native.Caller.scanElement(slot, "fillbar");
	previewFillingMaskBar=previewFillingBar.duplicateMovieClip("masker", previewFillingBar._parent.getNextHighestDepth());
	previewFillingBar.setMask(previewFillingMaskBar);

	var cacheFillingBar=mlf.gatekeeper.native.Caller.scanElement(slot, "cachebar");
	cacheFillingMaskBar=cacheFillingBar.duplicateMovieClip("cachemasker", cacheFillingBar._parent.getNextHighestDepth());
	cacheFillingBar.setMask(cacheFillingMaskBar);

	var progressFillingBar=mlf.gatekeeper.native.Caller.scanElement(slot, "pfillbar");
	progressFillingMaskBar=progressFillingBar.duplicateMovieClip("masker", progressFillingBar._parent.getNextHighestDepth());
	progressFillingBar.setMask(progressFillingMaskBar);

	currentStatus="idle";
	currentFilteredAudioObj=new Object();

	addConvertProgressListener();
}

function addConvertProgressListener()
{
	var nc=Packages.system.MLF.accessDefaultConnection();
	if (nc.isConnected==true)
	{
		// trace("register onFilterProgress...");
		nc.onFilterProgress=function(inputFileName:String, percentage:Number) 
		{
			// trace("onFilterProgress...input:"+inputFileName+" percentage:"+percentage);
			progressFillingMaskBar._x=percentage/100*progressFillingMaskBar._width-progressFillingMaskBar._width+125;
			displayTimePeriod(progressDisplay, Math.floor(Number(currentFilteredAudioObj.preAssignedDuration)*percentage/100), Number(currentFilteredAudioObj.preAssignedDuration));

			if (percentage==100)
			{
				convertorRunning=false;
		Packages.system.Platform.messageHint("ReadingRecorder", "", "normal");	//
				currentFilteredAudioObj.filteredAudioId=currentFilteredAudioObj.preAssignedAudioId;
				Packages.task.Composition.filteredAudioId=currentFilteredAudioObj.filteredAudioId;
				currentFilteredAudioObj.filteredDuration=currentFilteredAudioObj.preAssignedDuration;
				 trace("filteredDuration: "+currentFilteredAudioObj.filteredDuration);

				if (currentFilteredAudioObj.filteredDuration==Packages.task.Composition.processData.duration)
				{
					var cont:String=Packages.system.MLF.scanDictionary(Packages.components.ReadingRecorder.recorderMain, "processResult10");
	Packages.components.ReadingRecorder.refreshResultContent(cont, true);
				}
			}
		}
	}
}

// TODO: saveAuido and getAudioDuration
// Packages.task.Composition.processData
// processData.duration

function pressPreview(param, data, slot)
{
	Packages.system.Platform.highlightBG(mlf.mcmanager.PathResolver.extractPath(param), mlf.gatekeeper.native.Caller.scanElement(slot, "highlightBg"), 100);	
}

function rolloverPreview(param, data, slot)
{
	mlf.mcmanager.PathResolver.extractPath(param+"Bg")._visible=false;
	Packages.system.Platform.highlightBG(mlf.mcmanager.PathResolver.extractPath(param), mlf.gatekeeper.native.Caller.scanElement(slot, "highlightBg"), 50);	
}

function rolloutPreview(param, data, slot)
{
	mlf.mcmanager.PathResolver.extractPath(param+"Bg")._visible=true;
	Packages.system.Platform.highlightBG(mlf.mcmanager.PathResolver.extractPath(param), mlf.gatekeeper.native.Caller.scanElement(slot, "highlightBg"), 0);	
}

function releasePreview(param, data, slot)
{
	if (currentStatus=="idle" && !playerEngineRunning)
	{
		var audioContent;
		if (currentFilteredAudioObj.filteredAudioId==null)
		{
			audioContent=generateMLVbyAudioId(Packages.task.Composition.audioId, "flv");
		}
		else 
		{
			audioContent=generateMLVbyAudioId(currentFilteredAudioObj.filteredAudioId, "mp3");
		}
		var playArea=mlf.gatekeeper.native.Caller.scanElement(slot, "previewaudio");
		// trace("playArea: "+playArea);
		var param=new Object();
		param.target=playArea;
			
		param.type="file";
		param.source=new XML(audioContent);

		trace(applications.prototype.Logic.run("Version"));
		Packages.system.MLF.addListener("onPlayback", this);
		 applications.prototype.Logic.run("Open", param);

		currentStatus="play";
		var previewHint=mlf.gatekeeper.native.Caller.scanElement(slot, "previewHint");
		previewHint.htmlText=Packages.system.MLF.scanDictionary(previewFillingMaskBar, "Stop");
	}
	else if (currentStatus=="play")
	{
		applications.prototype.Logic.run("Stop");
		currentStatus="idle";
		var previewHint=mlf.gatekeeper.native.Caller.scanElement(slot, "previewHint");
		previewHint.htmlText=Packages.system.MLF.scanDictionary(previewFillingMaskBar, "Preview");
	}
	rolloutPreview(param, data, slot);
}

function mSeek(param, data, slot)
{
	var num=Math.floor(data.pos/previewFillingMaskBar._width*previewDuration);
	 applications.prototype.Logic.run("Seek", num);
}

function onPlayback(obj)
{
	// trace("onPlayback: "+obj.param.type);
	if (obj.param.type=="playback")
	{
		
		/*if (previewDuration==0) previewDuration=applications.prototype.Logic.run("Duration");*/
		previewFillingMaskBar._x=obj.param.param/previewDuration*previewFillingMaskBar._width-previewFillingMaskBar._width+125;
		displayTimePeriod(timeDisplay, Number(obj.param.param), Number(previewDuration));

	}
	else if (obj.param.type=="progress")
	{
		var totalBytes=obj.param.param.bytesLoaded;
		var todoBytes=0;
		var progressStatus=obj.param.param.progress;
		for (var b in progressStatus)
		{
			if (progressStatus[b].bytesTotal!=null)
			{
				todoBytes+=(progressStatus[b].bytesTotal-progressStatus[b].bytesLoaded);
			}
		}
		var cprogress=1-todoBytes/(todoBytes+totalBytes);
		trace("cprogress: "+cprogress);
		cacheFillingMaskBar._x=cprogress*cacheFillingMaskBar._width-cacheFillingMaskBar._width+125;

		if (!onceFlag && cprogress>0.1 && cprogress<1)
		{
			var mode:Object=new Object();
			mode.processKeeper=applications.prototype.Logic.run("Count");
			applications.prototype.Logic.run("Mode", mode);
			onceFlag=true;
		}

		if (obj.param.param.unloaded==0)
		{
			var mode:Object=new Object();
			mode.syncRef="audio0";
			applications.prototype.Logic.run("Mode", mode);
		}
	}
	else if (obj.param.type=="overPlay")
	{
		// previewDuration=0;
		Packages.system.MLF.removeListener("onPlayback", this);
		playerEngineRunning=false;
		currentStatus="idle";
		var previewHint=mlf.gatekeeper.native.Caller.scanElement("PostProduction", "previewHint");
		previewHint.htmlText=Packages.system.MLF.scanDictionary(previewFillingMaskBar, "Preview");
	}
	else if (obj.param.type=="readyPlay")
	{
		onceFlag=false;
		playerEngineRunning=true;
	}
}

function displayTimePeriod(display_tf:TextField, progress:Number, duration:Number)
{
	display_tf.text="[ "+calculateTimeFormat(progress)+" / "+calculateTimeFormat(duration)+" ]";
}

function calculateTimeSecond(tformat:String):Number
{
	var tEleArr=tformat.split(":");
	var totalSeconds=Number(tEleArr[2])+Number(tEleArr[1])*60+Number(tEleArr[0])*3600;
	// trace("totalSeconds: "+totalSeconds);
	return totalSeconds;
}

function calculateTimeFormat(seconds:Number):String
{
	var result:String="";

	var hour=Math.floor(seconds/3600);
	if (hour.toString().length==1)
	{
		result="0"+hour;
	}
	else result=hour;
	var minute=Math.floor((seconds-hour*3600)/60);
	if (minute.toString().length==1)
	{
		result+=":0"+minute;
	}
	else result+=":"+minute;
	var second=Math.floor(seconds-hour*3600-minute*60);
	if (second.toString().length==1)
	{
		result+=":0"+second;
	}
	else result+=":"+second;

	return result;
}

function generateMLVbyAudioId(audioId:String, type:String):String
{
	var duration:Number;
	var tagType:String;
	if (type=="mp3")
	{
		tagType="audio";
		duration=currentFilteredAudioObj.filteredDuration;
		previewDuration=duration;
		// trace("duration: "+duration);
	}
	else // flv type
	{
		tagType=type;
		duration=Packages.task.Composition.processData.duration;
	}
	var mlvString:String="";
	var audioURI:String=Packages.system.Util.getHttpBaseUrl()+"/tmp/audio/"+audioId+"."+type;
	mlvString+="<mlv duration='"+duration+"' name='MLV' info='designed by blue night'>";
	mlvString+="<resource>";
	mlvString+="<"+tagType+" name='audio0' uri='"+audioURI+"'/>";
	mlvString+="</resource>";
	mlvString+="<playback>";
	mlvString+="<clip name='audio0_c1' signpost='0' length='"+duration+"' layer='10' ref='audio0'/>";
	mlvString+="</playback>";
	mlvString+="</mlv>";
	trace("mlvString: "+mlvString);

	return mlvString;
}

function pressConvert(param, data, slot)
{
	if (convertorRunning) return;
	Packages.system.Platform.highlightBG(mlf.mcmanager.PathResolver.extractPath(param), mlf.gatekeeper.native.Caller.scanElement(slot, "highlightBg2"), 100);	
}

function rolloverConvert(param, data, slot)
{
	if (convertorRunning) return;
	
	mlf.mcmanager.PathResolver.extractPath(param+"Bg")._visible=false;
	Packages.system.Platform.highlightBG(mlf.mcmanager.PathResolver.extractPath(param), mlf.gatekeeper.native.Caller.scanElement(slot, "highlightBg2"), 50);	
}

function rolloutConvert(param, data, slot)
{
	mlf.mcmanager.PathResolver.extractPath(param+"Bg")._visible=true;
	Packages.system.Platform.highlightBG(mlf.mcmanager.PathResolver.extractPath(param), mlf.gatekeeper.native.Caller.scanElement(slot, "highlightBg2"), 0);	
}

function releaseConvert(param, data, slot)
{
	if (convertorRunning) return;
	// convertFlv2Mp3(data);
	convertorRunning=true;
	Packages.system.Platform.messageHint("ReadingRecorder", Packages.system.MLF.scanDictionary(previewFillingMaskBar, "converting"), "warning");	//
	generateCurrentAudioId(data);
	rolloutConvert(param, data, slot);
}

function convertFlv2Mp3(data)
{
	var sampleRate=0;
	if (data.sampleRate=="11") sampleRate=11025;
	else if (data.sampleRate=="22") sampleRate=22050;
	else if (data.sampleRate=="44") sampleRate=44100;
	var item=new Object();
	item.type="filterAudio";
	item.param=new Object();
	item.param.input=Packages.task.Composition.audioId+".flv";
	item.param.output=currentFilteredAudioObj.preAssignedAudioId+".mp3";
	item.param.bitRate=data.bitRate;
	item.param.sampleRate=sampleRate;
	item.param.volume=data.volume;
	item.param.startTime=0;
	if (data.startTime!=null)
	{
		item.param.startTime=calculateTimeSecond(data.startTime);
	}
	item.param.duration=-1;
	currentFilteredAudioObj.preAssignedDuration=Packages.task.Composition.processData.duration;
	if (data.endTime!=null)
	{
		item.param.duration=calculateTimeSecond(data.endTime)-calculateTimeSecond(data.startTime);

		currentFilteredAudioObj.preAssignedDuration=item.param.duration;
	}
	// trace("preAssignedDuration: "+currentFilteredAudioObj.preAssignedDuration);
	//item.param.numChannels=0;
	//item.param.sizeLimit=-1;
	for (var a in item.param)
	{
		trace(a+": "+item.param[a]);
	}

	item.result=new Object();
	item.result.owner=this;
	item.result.onResult=function(res)
	{
		trace("filterAudio.obj.returnCode: "+res.returnCode);
		if (res.returnCode!=0)
		{
			convertorRunning=false;
			Packages.system.Platform.messageHint("ReadingRecorder", Packages.system.MLF.scanDictionary(previewFillingMaskBar, "convertingFailed"), "warning");
		}
	}   
	Packages.system.MLF.rtmpCaller(item);
}

function generateCurrentAudioId(data)
{
	var refData=data;
	var item=new Object();
	item.type="generateUuid";
	item.param=new Object();
	item.result=new Object();
	item.result.owner=this;
	item.result.onResult=function(res)
	{
		trace("generateAudioId.onResult: "+res.returnObj);
		if (res.returnObj!=null)
		{
			this.owner.currentFilteredAudioObj.preAssignedAudioId=res.returnObj;
			this.owner.convertFlv2Mp3(refData);
		}
	}	
	Packages.system.MLF.rtmpCaller(item);
}